<template>
  <el-autocomplete
  v-bind="fld"
  :fetch-suggestions="querySearch"
  :value="value"
  @input="handleModelInput"
  @select="handleSelect"
  size="mini"
  ></el-autocomplete>
</template>
<script type="text/javascript">
  define(['vue'],function(vue){
    //autocomplete
    return vue.component('comp-autocomplete',{
      // props:['fld','value'],
      props : {
        fld :{required:false,},
        value :{required:false,default:function(){
          return '';
        }},
      },
      data(){
        return {
          action:this.fld.action,
          options:this.fld.options||[],
        }
      },
      /*源码中,suggestion点击后触发的动作如下:
      select(item) {
            this.$emit('input', item[this.valueKey]);
            this.$emit('select', item);
            this.$nextTick(_ => {
              this.suggestions = [];
              this.highlightedIndex = -1;
            });
          },
      */
      template: template,
      methods:{
        querySearch : function(queryString, cb) {
          if(!this.action) {
            //从静态数组中筛选
            var ret = [];
            var key = this.valueKey || 'value';
            for(var i=0;this.options[i];i++) {
              if(this.options[i][key].indexOf((queryString||'').toLowerCase())==-1) continue;
              ret.push(this.options[i]);
            }
            cb(ret);
            return;
          }
          var ret = [];
          var params={key:this.value};
          //可能会有一些页面的其他参数需要动态获得后作为参数加入

          this.$http.post(this.action,params).then((res)=>{
            if(!res.data.success) {
              dump(res.msg||'出错');
              return false;
            }
            // dump(res.data);
            cb(res.data.data);
          }).catch(function (error) {
            dump(error);
          });
          // var options  = this.fld.options || [];
          // var results = queryString ? options.filter(this.createFilter(queryString)) : options;
          // cb(results);
        },
        // createFilter(queryString) {
        //   return (restaurant) => {
        //     return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        //   };
        // },
        handleModelInput :function(val){
          this.$emit("input", val);
        },
        handleSelect : function(item) {
          var key = `${this.fld.name}:select`;
          if(!this.$root.callbacks[key]) return;
          this.$root.callbacks[key].apply(this,arguments);
          // this.$emit("select", `${this.fld.name}:select`, item);
        },
        //比如主从表中，子表控件获得焦点，当前行中，改变订单后联动改变相关客户等效果
        handlFocus() {
          var key = `${this.fld.name}:focus`;
          if(!this.$root.callbacks[key]) return;
          this.$root.callbacks[key].apply(this,arguments);
        }
      },
      mounted:function(){
        if(this.value==undefined) {
          console.warn(`comp-autocomplete组件错误:数据集中的[${this.fld.name}]字段没有默认值`);
        }
      }
    });
  });
</script>